package servlet;

import bean.Activity;
import bean.PageBean;
import dao.ActivityDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created by lenovo-66 on 2017/11/2.
 * 骑行用户对activity的请求处理
 */
public class UserActivityServlet extends HttpServlet {

    private ActivityDao activityDao = new ActivityDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        JsonWrapper result = new JsonWrapper();

        // 分页
        String start = req.getParameter("start");  //当前页
        String pageSize = req.getParameter("pagesize");  //页记录数
        PageBean pageBean;
        if (start != null && pageSize != null) {
            int s = 0;
            int ps = 0;
            if (!StringUtil.isEmpty(start)) {
                s = Integer.parseInt(start);
            }
            if (!StringUtil.isEmpty(pageSize)) {
                ps = Integer.parseInt(pageSize);
            }
            pageBean = new PageBean(s, ps);
        } else {
            pageBean = null;
        }

        String userId = req.getParameter("userId");
        String activityId = req.getParameter("activityId");
        if (userId != null) { //查询用户创建的活动
            List<Object> resultActivity;  //查询返回的活动信息
            JSONArray jsonArray = new JSONArray();
            Activity activity = new Activity();
            activity.setUserId(userId);
            try {
                resultActivity = activityDao.activityList(pageBean, activity, null, null, null, null, null, null);
                if (resultActivity.size() != 0) {
                    result.setStatus(200);
                    result.setMsg("success");
                } else {
                    result.setStatus(200);
                    result.setMsg("No record!");
                }

                for (Object single : resultActivity) {
                    JSONObject jsonObject = JsonWrapper.parseFromObject(single);
                    jsonArray.add(jsonObject);
                }
                result.setDataEntry("total", resultActivity.size());
                result.setDataJsonArray("values", jsonArray);
            } catch (Exception e) {
                //查询失败
                result.setStatus(401);
                result.setMsg("query failed");
                e.printStackTrace();
            }
        } else if (activityId == null) { //查询所有已批准的活动
            List<Object> resultActivity;  //查询返回的活动信息
            JSONArray jsonArray = new JSONArray();
            Activity activity = new Activity();
            activity.setStatus("2");
            try {
                resultActivity = activityDao.activityList(pageBean, activity, null, null, null, null, null, null);
                if (resultActivity.size() != 0) {
                    result.setStatus(200);
                    result.setMsg("success");
                } else {
                    result.setStatus(200);
                    result.setMsg("No record!");
                }

                for (Object single : resultActivity) {
                    JSONObject jsonObject = JsonWrapper.parseFromObject(single);
                    jsonArray.add(jsonObject);
                }
                result.setDataEntry("total", resultActivity.size());
                result.setDataJsonArray("values", jsonArray);
            } catch (Exception e) {
                //查询失败
                result.setStatus(401);
                result.setMsg("query failed");
                e.printStackTrace();
            }
        }

        if (activityId != null) { //查询某个活动详情
            List<Object> resultAdvice;  //查询返回的用户信息
            try {
                resultAdvice = activityDao.activityList(null, new Activity(activityId), null, null, null, null, null, null);

                int total = resultAdvice.size();
                if (total != 0) {
                    activityDao.activityClick(activityId);//点击量加一
                    result.setMsg("success");
                } else {
                    result.setMsg("no record!");
                }
                result.setStatus(200);
                result.setDataEntry("total", total);
                result.setDataObject("value", total == 0 ? new JSONObject() : resultAdvice.get(0));
            } catch (Exception e) {
                result.setStatus(401);  //查询失败
                result.setMsg("failed");
                e.printStackTrace();
            }
        }
        ResponseUtil.write(resp, result.get());
    }

    /**
     * 增加
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JSONObject json = RequestUtil.getJsonFromRequest(req);
        if (json != null) {
            Activity activity = new Activity();
            activity.setUserId(json.getString("creator"));
            activity.setTitle(json.getString("title"));
            String now1 = DateUtil.nowTime();
            String now2 = DateUtil.parseTime(now1);
            Date time = DateUtil.parse(now2);
            activity.setCreateTime(now2);
            Long startTime = json.getLong("startTime");
            Long endTime = json.getLong("endTime");
            Date time1 = new Date(startTime);
            Date time2 = new Date(endTime);
            activity.setStartTime(DateUtil.getStringDate(time1));
            activity.setEndTime(DateUtil.getStringDate(time2));
            activity.setDescription(json.getString("description"));
            activity.setStatus("-1");
            activity.setTempCount("0");
            String maxCount = json.getString("maxUserCount");
            if (maxCount != null) {
                activity.setMaxUserCount(maxCount);
            } else {
                activity.setMaxUserCount("50");
            }
            activity.setClick("0");

            JsonWrapper result = new JsonWrapper();

            try {
                boolean rightTime = time.getTime() <= time1.getTime() && time1.getTime() < time2.getTime();
                if (rightTime) {
                    boolean result1 = activityDao.activityAdd(activity);
                    if (result1) {
                        result.setStatus(200);  //
                        result.setMsg("success");
                        result.setDataEntry("total", 1);
                    } else {
                        result.setStatus(400);  //
                        result.setMsg("数据库更新失败");
                    }
                } else {
                    result.setStatus(400);  //
                    result.setMsg("请确保创建时间<=开始时间<结束时间");
                }
            } catch (Exception e) {
                result.setStatus(401);  //
                result.setMsg("failed");
                e.printStackTrace();
            }
            ResponseUtil.write(resp, result.get());
        } else {
            ResponseUtil.write(resp, JsonWrapper.builder().setStatus(400).setMsg("failed").build());
        }
    }
}
